<?php
/**
 * Created by PhpStorm.
 * User: davin
 * Date: 14-10-26
 * Time: 下午9:28
 */
class FileController extends Controller {

    protected $uploadHandler;
    protected $slash = DIRECTORY_SEPARATOR;
    public function __construct(){

        $options = array(
            'upload_dir' => storage_path() . $this->slash . 'uploads' . $this->slash . 'images' . $this->slash,
            'upload_url' => URL::to('file/image?name='),
            'param_name' => 'upload',
            'discard_aborted_uploads' => false,
            'max_file_size' => 1024*1024*2
        );

        $this->uploadHandler = new UploadHandler($options, false, false);

        if($this->uploadHandler->get_server_var('REQUEST_METHOD')== 'OPTIONS'|| $this->uploadHandler->get_server_var('REQUEST_METHOD')== 'HEAD'){
            $this->head();
        }
    }
    /**
     * Admin images
     *
     */
    public function postCkUpload()
    {
        $response = $this->uploadHandler->post(false);
        $message = '';
        $url='';

        if(is_array($response['upload']) && count($response['upload'])>0){
            $file = $response['upload'][0];
            if(isset($file->error)){
                $message = $file->error;
            }else{
                $url = $file->url;
            }
        }else {
            $message = "";
        }
        //$name = time()."_".$_FILES['upload']['name'];

        $funcNum = $_GET['CKEditorFuncNum'] ;
        echo "<script type='text/javascript'>window.parent.CKEDITOR.tools.callFunction($funcNum, '$url', '$message');</script>";
    }

    public function postImageUpload(){
        $this->uploadHandler->setUploadDir(storage_path() . $this->slash . 'uploads' . $this->slash . 'images' . $this->slash);
        $this->uploadHandler->post();
    }

    public function getImageUpload(){
        $this->uploadHandler->setUploadDir(storage_path() . $this->slash . 'uploads' . $this->slash . 'images' . $this->slash);
        ob_clean();
        $this->uploadHandler->get();
    }
    public function deleteImageUpload(){
        $this->uploadHandler->delete();
        $paths = Input::get('upload');
        if(is_array($paths)){
            foreach($paths as $path){
                $thumb = Thumb::where('path', $path)->get()->first();
                if($thumb) $thumb->delete();
            }
        }
    }

    public function postFileUpload(){
        $this->uploadHandler->setUploadDir(public_path() . $this->slash . 'files' . $this->slash);
        $this->uploadHandler->post();
    }

    public function deleteSendDocumentUpload(){
        $this->uploadHandler->setUploadDir(public_path() . $this->slash . 'documents' . $this->slash);
        $this->uploadHandler->delete(false);
        if(Input::get('id', null)!=null){
//            $id = (int)Input::get('id');
//            $attachment = DocumentAttachment::find($id);
//            $attachment->delete();
        }
        $url = (is_array(Input::get('upload'))&&count(Input::get('upload'))>0)?Input::get('upload')[0]:'';
        return Array('result'=>true,'url'=>$url);
    }

    public function getImage(){
        $imgsrc = storage_path().'/uploads/images/'.Input::get('name');
        //加载默认图片
        if(!file_exists($imgsrc)){
            $imgsrc = public_path().'/assets/img/default.jpg';
        }

        $info=getimagesize($imgsrc);
        ob_clean();
        header("content-type:".$info['mime']);
        echo fread(fopen($imgsrc,'rb'),filesize($imgsrc));
    }

    public function getImageCrop($sx,$sy,$targetWidth = 0){

        $imgsrc = storage_path().'/uploads/images/'.Input::get('name');
        //判断服务器是否有图片，有就下载
        if(!file_exists($imgsrc)){
            $return_content = $this->http_get_data(Config::get('app.domain').'/file/image?name='.Input::get('name'));
            $fp= fopen($imgsrc,"w");
            fwrite($fp,$return_content);
        }
        //加载默认图片
        if(!file_exists($imgsrc)){
            $imgsrc = public_path().'/assets/img/default.jpg';
        }

        list($width, $height) = getimagesize($imgsrc);
        $width = ($targetWidth == 0) ? $width : $targetWidth;
        if($width>$height){ //修改
            $newwidth = $width;
            $newheight = $width * $sy / $sx;
        }else{
            $newwidth = $height * $sx / $sy;
            $newheight = $height;
        }

        $this->imagecropper($imgsrc, $newwidth, $newheight);
    }

    public function getThumbnail(){
        $imgsrc = storage_path().'/uploads/images/thumbnail/'.Input::get('name');
        $info=getimagesize($imgsrc);
        ob_clean();
        header("content-type:".$info['mime']);
        echo fread(fopen($imgsrc,'rb'),filesize($imgsrc));
    }

    function imagecropper($source_path, $target_width, $target_height)
    {
        $source_info   = getimagesize($source_path);
        $source_width  = $source_info[0];
        $source_height = $source_info[1];
        $source_mime   = $source_info['mime'];
        $source_ratio  = $source_height / $source_width;
        $target_ratio  = $target_height / $target_width;

        // 源图过高
        if ($source_ratio > $target_ratio)
        {
            $cropped_width  = $source_width;
            $cropped_height = $source_width * $target_ratio;
            $source_x = 0;
            $source_y = ($source_height - $cropped_height) / 2;
        }
        // 源图过宽
        elseif ($source_ratio < $target_ratio)
        {
            $cropped_width  = $source_height / $target_ratio;
            $cropped_height = $source_height;
            $source_x = ($source_width - $cropped_width) / 2;
            $source_y = 0;
        }
        // 源图适中
        else
        {
            $cropped_width  = $source_width;
            $cropped_height = $source_height;
            $source_x = 0;
            $source_y = 0;
        }

        switch ($source_mime)
        {
            case 'image/gif':
                $source_image = imagecreatefromgif($source_path);
                break;

            case 'image/jpeg':
                $source_image = imagecreatefromjpeg($source_path);
                break;

            case 'image/png':
                $source_image = imagecreatefrompng($source_path);
                break;

            default:
                return false;
                break;
        }

        $target_image  = imagecreatetruecolor($target_width, $target_height);
        $cropped_image = imagecreatetruecolor($cropped_width, $cropped_height);

        // 裁剪
        imagecopy($cropped_image, $source_image, 0, 0, $source_x, $source_y, $cropped_width, $cropped_height);
        // 缩放
        imagecopyresampled($target_image, $cropped_image, 0, 0, 0, 0, $target_width, $target_height, $cropped_width, $cropped_height);

        ob_clean();
        header('Content-Type: image/jpeg');
        imagejpeg($target_image);
        imagedestroy($source_image);
        imagedestroy($target_image);
        imagedestroy($cropped_image);
    }

    function http_get_data($url) {

        $ch = curl_init ();
        curl_setopt ( $ch, CURLOPT_CUSTOMREQUEST, 'GET' );
        curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, false );
        curl_setopt ( $ch, CURLOPT_URL, $url );
        ob_start ();
        curl_exec ( $ch );
        $return_content = ob_get_contents ();
        ob_end_clean ();

        $return_code = curl_getinfo ( $ch, CURLINFO_HTTP_CODE );
        return $return_content;
    }


}